import webSocket from '@ohos.net.webSocket';

var wsAddress = "wss://";
let ws = webSocket.createWebSocket();
export default {
    data: {
        id:1,
        title: "",
        message:[{
                     postId:0,
                     message:"I am ID 0!"
                 },{
            postId:1,
            message:"I am ID 1!"
        }],
        sendMes:""
    },
    onInit() {
        let that = this;
        ws.connect(wsAddress, (err, value) => {
            if (!err) {
                console.log("xxx---connect success");
            } else {
                console.log("xxx---connect fail, err:" + JSON.stringify(err));
            }
        });
        ws.on('message', (err, value) => {
            console.log("xxx---on message, message:" + value);
            //传递的是序列化后的字符串，需要解序列化为JSON对象
            let dataObj = JSON.parse(value)
            console.log("xxx---parse success---postId: "+dataObj.postId+",message:"+dataObj.message)
            that.message.push(dataObj)
            console.log("xxx---check message: "+JSON.stringify(that.message))
            // 当收到服务器的`bye`消息时（此消息字段仅为示意，具体字段需要与服务器协商），主动断开连接
            if (value === 'bye') {
                ws.close((err, value) => {
                    if (!err) {
                        console.log("xxx---close success");
                    } else {
                        console.log("xxx---close fail, err is " + JSON.stringify(err));
                    }
                });
            }
        });
    },
    sendMessage(){
        let that  = this;
        let data = {
            postId:that.id,
            message:that.sendMes
        }
        let dataStr = JSON.stringify(data)
        ws.send(dataStr, (err, value) => {
            if (!err) {
                console.log("xxx---send success");
            } else {
                console.log("xxx---send fail, err:" + JSON.stringify(err));
            }
        });
        that.message.push(data)
    },
    inputChange(e){
        this.sendMes = e.text
        console.log("xxx---input change:  "+e.text)
        console.log("xxx---获取textarea输入： "+this.sendMes)
    }

}
